// 定义类型接口
export interface DeviceInfo {
    deviceId: string
    deviceName: string
    status: DeviceStatus
    productionCount: number
    temperature: number
    speed: number
    alarmMessage: string
    timestamp: number
    location: string
}

export interface DeviceStatusUpdate {
    devices: DeviceInfo[]
    serverTimestamp: number
}

export enum DeviceStatus {
    UNKNOWN = 0,
    RUNNING = 1,
    STOPPED = 2,
    ALARM = 3,
    MAINTENANCE = 4
}

export class DeviceMonitoringClient {
    private baseUrl: string
    private activeStream: any = null
    private reconnectAttempts = 0
    private maxReconnectAttempts = 5
    private reconnectDelay = 1000

    constructor(baseUrl: string = import.meta.env.VITE_APP_API_URL_WS) {
        this.baseUrl = baseUrl
    }

    // 订阅设备状态流 - 使用长轮询模拟gRPC流
    subscribeToDeviceStatus(
        clientId: string,
        onUpdate: (update: DeviceStatusUpdate) => void,
        onError?: (error: any) => void,
        onEnd?: () => void
    ): void {
        console.log(`开始订阅设备状态，客户端ID: ${clientId}`)
        this.startPolling(clientId, onUpdate, onError, onEnd)
    }

    private async startPolling(
        clientId: string,
        onUpdate: (update: DeviceStatusUpdate) => void,
        onError?: (error: any) => void,
        onEnd?: () => void
    ): Promise<void> {
        let shouldContinue = true

        const poll = async () => {
            try {
                const response = await fetch(`${this.baseUrl}/api/devices/status`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Client-Id': clientId
                    }
                })

                if (response.ok) {
                    const data = await response.json()
                    this.reconnectAttempts = 0
                    onUpdate(data)
                }
            } catch (error) {
                console.error('轮询错误:', error)
                if (this.reconnectAttempts < this.maxReconnectAttempts) {
                    this.reconnectAttempts++
                    console.log(`${this.reconnectDelay}ms后重试第${this.reconnectAttempts}次...`)
                } else {
                    shouldContinue = false
                    onError?.(error)
                    return
                }
            }

            if (shouldContinue) {
                setTimeout(poll, 500) // 500ms轮询间隔
            }
        }

        poll()
    }

    // 发送心跳
    async sendHeartbeat(clientId: string): Promise<boolean> {
        try {
            const response = await fetch(`${this.baseUrl}/api/devices/heartbeat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Client-Id': clientId
                },
                body: JSON.stringify({ clientId })
            })

            const result = await response.json()
            return result.success
        } catch (error) {
            console.error('心跳失败:', error)
            return false
        }
    }

    // 获取所有设备当前状态
    async getAllDevicesStatus(clientId: string): Promise<DeviceStatusUpdate> {
        try {
            const response = await fetch(`${this.baseUrl}/api/devices/all`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Client-Id': clientId
                }
            })

            return await response.json()
        } catch (error) {
            console.error('获取设备状态失败:', error)
            throw error
        }
    }

    // 断开连接
    disconnect(): void {
        if (this.activeStream) {
            this.activeStream = null
            console.log('连接已断开')
        }
    }
} 